<template>
  <div class="tag-search-container">
    <!-- 标签搜索区域 -->
    <div class="tag-search-header">
      <span class="tag-label">标签筛选：</span>
      <a class="clear-all" @click="clearAllTags" v-if="selectedTags.length > 0">清除所有</a>
    </div>
    
    <!-- 标签输入框 -->
    <div class="tag-input-container">
      <div class="el-input el-input--suffix tag-input-wrapper">
        <div class="selected-tags-container">
          <el-tag
            v-for="tag in selectedTags"
            :key="tag.value"
            closable
            class="selected-tag"
            @close="removeTag(tag)"
          >
            {{ tag.label }}
          </el-tag>
          <input
            class="tag-input"
            v-model="searchText"
            placeholder="请输入标签关键字搜索"
            @input="handleInput"
            @focus="showSuggestions = true"
            @blur="handleBlur"
            @keydown.delete="handleDelete"
          />
        </div>
        <span class="el-input__suffix" v-if="searchText || selectedTags.length > 0">
          <span class="el-input__suffix-inner">
            <i class="el-icon-circle-close el-input__clear" @click="clearInput"></i>
          </span>
        </span>
      </div>
      
      <!-- 标签候选列表 -->
      <div class="tag-suggestions" v-if="showSuggestions && filteredTags.length > 0">
        <div
          v-for="tag in filteredTags"
          :key="tag.value"
          class="tag-suggestion-item"
          @mousedown="selectTag(tag)"
          :class="{ 'is-active': highlightedIndex === filteredTags.indexOf(tag) }"
        >
          {{ tag.label }}
        </div>
      </div>
    </div>
    
    <!-- 标签列表 -->
    <div class="tag-list">
      <el-tag
        v-for="tag in allTags"
        :key="tag.value"
        :type="isTagSelected(tag) ? '' : 'info'"
        effect="plain"
        class="tag-item"
        :class="{ 'active-tag': isTagSelected(tag) }"
        @click="toggleTag(tag)"
      >
        {{ tag.label }}
      </el-tag>
    </div>
    
    <!-- 文章列表 -->
    <el-table :data="filteredArticles" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="title" label="文章标题"></el-table-column>
      <el-table-column prop="category" label="分类"></el-table-column>
      <el-table-column prop="publishTime" label="发表时间"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" circle>
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button type="danger" size="small" circle>
            <el-icon><Delete /></el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'

// 搜索文本
const searchText = ref('')
const showSuggestions = ref(false)
const highlightedIndex = ref(-1)

// 所有可用标签
const allTags = ref([
  { label: '计算机专业', value: 'computer-science' },
  { label: '高考', value: 'college-exam' },
  { label: '大学', value: 'university' },
  { label: '软件工程', value: 'software-engineering' },
  { label: '编程入门', value: 'programming-intro' },
  { label: '计算机技术', value: 'computer-tech' },
  { label: 'Web前端', value: 'web-frontend' }
])

// 已选标签
const selectedTags = ref([])

// 模拟文章数据
const articles = ref([
  {
    id: 1,
    title: '计算机科学导论',
    category: '计算机基础',
    publishTime: '2024-09-21 17:06:44',
    status: '已发布',
    tags: ['computer-science', 'programming-intro']
  },
  {
    id: 2,
    title: 'Vue3基础教程',
    category: '编程教程',
    publishTime: '2024-09-20 10:15:30',
    status: '已发布',
    tags: ['programming-intro', 'web-frontend']
  },
  {
    id: 3,
    title: '高考备考指南',
    category: '教育',
    publishTime: '2024-09-19 14:22:10',
    status: '已发布',
    tags: ['college-exam']
  },
  {
    id: 4,
    title: '软件工程最佳实践',
    category: '技术',
    publishTime: '2024-09-18 09:45:22',
    status: '未发布',
    tags: ['software-engineering', 'computer-science']
  }
])

// 根据搜索文本过滤标签
const filteredTags = computed(() => {
  if (!searchText.value) return allTags.value.filter(tag => !isTagSelected(tag))

  return allTags.value.filter(tag =>
    tag.label.toLowerCase().includes(searchText.value.toLowerCase()) &&
    !isTagSelected(tag)
  )
})

// 根据选中的标签过滤文章
const filteredArticles = computed(() => {
  if (selectedTags.value.length === 0) return articles.value

  return articles.value.filter(article =>
    selectedTags.value.some(tag => article.tags.includes(tag.value))
  )
})

// 检查标签是否已选中
const isTagSelected = (tag) => {
  return selectedTags.value.some(t => t.value === tag.value)
}

// 处理输入事件
const handleInput = () => {
  showSuggestions.value = true
  highlightedIndex.value = -1
}

// 处理失焦事件
const handleBlur = () => {
  // 延迟关闭建议列表，以便点击事件可以先触发
  setTimeout(() => {
    showSuggestions.value = false
    searchText.value = ''
  }, 200)
}

// 处理删除键事件
const handleDelete = (event) => {
  if (searchText.value === '' && selectedTags.value.length > 0) {
    // 如果搜索框为空且有选中的标签，则删除最后一个标签
    removeTag(selectedTags.value[selectedTags.value.length - 1])
  }
}

// 选择标签
const selectTag = (tag) => {
  if (!isTagSelected(tag)) {
    selectedTags.value.push(tag)
    searchText.value = ''
    nextTick(() => {
      showSuggestions.value = false
    })
  }
}

// 切换标签选中状态
const toggleTag = (tag) => {
  if (isTagSelected(tag)) {
    removeTag(tag)
  } else {
    selectedTags.value.push(tag)
  }
}

// 移除标签
const removeTag = (tag) => {
  selectedTags.value = selectedTags.value.filter(t => t.value !== tag.value)
}

// 清除所有标签
const clearAllTags = () => {
  selectedTags.value = []
}

// 清除输入框
const clearInput = () => {
  searchText.value = ''
  selectedTags.value = []
}
</script>

<style scoped>
.tag-search-container {
  width: 100%;
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.tag-search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.tag-label {
  font-size: 14px;
  color: #606266;
}

.clear-all {
  color: #409EFF;
  cursor: pointer;
  font-size: 14px;
}

.tag-input-container {
  position: relative;
  margin-bottom: 16px;
}

.tag-input-wrapper {
  width: 100%;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 0 30px 0 5px;
  min-height: 40px;
  display: flex;
  align-items: center;
  background-color: #fff;
}

.tag-input-wrapper:hover {
  border-color: #C0C4CC;
}

.tag-input-wrapper:focus-within {
  border-color: #409EFF;
}

.selected-tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  flex: 1;
  padding: 3px 0;
}

.selected-tag {
  margin: 2px 4px 2px 0;
}

.tag-input {
  border: none;
  outline: none;
  flex: 1;
  min-width: 80px;
  height: 28px;
  padding: 0 5px;
  font-size: 14px;
}

.el-input__suffix {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #C0C4CC;
}

.el-input__suffix:hover {
  color: #909399;
}

.tag-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background-color: #fff;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 100;
  margin-top: 4px;
}

.tag-suggestion-item {
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
}

.tag-suggestion-item:hover,
.tag-suggestion-item.is-active {
  background-color: #F5F7FA;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 16px 0;
  padding: 12px 0;
  border-top: 1px solid #EBEEF5;
  border-bottom: 1px solid #EBEEF5;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s;
}

.tag-item:hover {
  transform: translateY(-2px);
}

.active-tag {
  font-weight: bold;
  transform: translateY(-2px);
}
</style>